package com.example.run_game;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.Date;

import org.apache.http.HttpStatus;

import com.google.android.gms.maps.model.LatLng;

import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PreRunMenu extends Activity {
	Dialog dialogSetTime;
	Dialog dialogSetDist;
	
	WeatherManager weather;
	
	private NumberPicker nphours;
	private NumberPicker npdist;
	private NumberPicker npmins;
	private boolean timeChecked = false;	
	
	Handler handler = null;
	
	private Player mPlayer;
	private DbManager db;
		
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //set view to current page
        setContentView(R.layout.activity_pre_run_menu); 
        
        setWeatherHandler();       
        weather = new WeatherManager(handler);
        
        db = new DbManager(this);
        mPlayer = new Player(db);
        Log.d("Player Profile", "DB Connection Made");
        populateProfileBar();
        
        //Create buttons and listeners for the two run options (Time and Distance)
        Button runTimeButton = (Button)findViewById(R.id.runTimeButton);
        runTimeButton.setOnClickListener(checkTimeRunPress);    
        
        Button runDistButton = (Button)findViewById(R.id.runDistButton);
        runDistButton.setOnClickListener(checkDistRunPress); 
                  
        //Create a custom dialog with the dialog_time.xml file
        dialogSetTime = new Dialog(this);
        dialogSetTime.setContentView(R.layout.dialog_time);
        dialogSetTime.setTitle("Run for Time");
        
        //Create a custom dialog with the dialog_dist.xml file
        dialogSetDist = new Dialog(this);
        dialogSetDist.setContentView(R.layout.dialog_dist);
        dialogSetDist.setTitle("Run by Distance");
        setupProgressBar();
              
    }
   

   private void populateProfileBar()
{
	// TODO Auto-generated method stub
	   ImageView profilePic = (ImageView)findViewById(R.id.list_image);
	   Bitmap picture = mPlayer.getPicture();
   	   if(picture != null)
   		   profilePic.setImageBitmap(picture);
   	   DecimalFormat df = new DecimalFormat("#.##");
   	   
   	   TextView playerName = (TextView)findViewById(R.id.title);
   	   playerName.setText(mPlayer.getName().toString());
   	   TextView distTime = (TextView)findViewById(R.id.distance);
	   distTime.setText("Total Dist/Time: "+df.format(mPlayer.getTotalDistance()/1000)+"km/"+ Utils.formatMilliTime(mPlayer.getTotalTime(),false));
	   TextView avSpeed = (TextView)findViewById(R.id.average_speed);
   	   avSpeed.setText("Average Speed: "+df.format(mPlayer.getAvSpeed()*60*60/1000)+" kph");
   	   TextView calories = (TextView)findViewById(R.id.calories);
	   calories.setText("Calories Burned: "+Integer.toString(mPlayer.getTotalCaloriesBurned()));
}
   
   private String convertTimeString(int totalSeconds){
   	
   	int hr = totalSeconds/3600;
		String h = hr<10?"0"+hr:hr==0?"00":hr+"";
		int m = (totalSeconds%3600)/60;
		int s = totalSeconds%60;
		String timeString = h+":"+m+":"+s;
		
   	return timeString;
   }


private void setWeatherHandler()
   {
	    System.out.println("GOT INTO SET HANDLER #####################");
		handler = new Handler()
		{
			public void handleMessage(Message msg)
			{
				System.out.println("HANDLE CREATED #####################");
				if (msg.what == 2)
				{
					String[] weather_stats = (String[]) msg.obj;
					TextView weatherType = (TextView)findViewById(R.id.weather_type);
				    weatherType.setText(weather_stats[1]);
				    TextView temperature = (TextView)findViewById(R.id.temperature);
				    double celsius = 0;
				    double fahrenheit = 0;
				    fahrenheit = Double.parseDouble(weather_stats[2]);
				    celsius = (fahrenheit-32)*5/9;
				    temperature.setText((int)celsius+" C");
				    TextView wind = (TextView)findViewById(R.id.wind);
				    int degrees = Integer.parseInt(weather_stats[3]);
				    String direction = "";
				    if ((degrees > 338 && degrees < 361) || (degrees > -1 && degrees < 24) ){
				    	direction = "N";
				    }
				    else if (degrees > 23 && degrees < 69){
				    	direction = "NE";
				    }
				    else if (degrees > 68 && degrees < 114){
				    	direction = "E";
				    }
				    else if (degrees > 113 && degrees < 159){
				    	direction = "SE";
				    }
				    else if (degrees > 158 && degrees < 204){
				    	direction = "S";
				    }
				    else if (degrees > 203 && degrees < 249){
				    	direction = "SW";
				    }
				    else if (degrees > 248 && degrees < 294){
				    	direction = "W";
				    }
				    else if (degrees > 293 && degrees < 339){
				    	direction = "NW";
				    }
				    wind.setText("Wind: "+direction+" at "+weather_stats[4]+" mph");
				    TextView updated = (TextView)findViewById(R.id.updated);
				    updated.setText(weather_stats[0]);
				   				    
				    String type = weather_stats[5];
				    ImageView weatherIcon = (ImageView)findViewById(R.id.weather_image);
					if(type.equals("26") || type.equals("28"))
					{
						weatherIcon.setImageDrawable(getResources().getDrawable(R.drawable.cloudy));
					}
					else if(type.equals("30") || type.equals("44"))
					{
						weatherIcon.setImageDrawable(getResources().getDrawable(R.drawable.sun_cloud));
					}
					else if(type.equals("11") || type.equals("12") || type.equals("9")|| type.equals("40")|| type.equals("9"))
					{
						weatherIcon.setImageDrawable(getResources().getDrawable(R.drawable.rain));
					}
					else if(type.equals("5") || type.equals("6") || type.equals("7")|| type.equals("8")|| type.equals("10")|| type.equals("35"))
					{
						weatherIcon.setImageDrawable(getResources().getDrawable(R.drawable.rain_snow));
					}
					else if(type.equals("13") || type.equals("14") || type.equals("15")|| type.equals("16")|| type.equals("17")|| type.equals("18")|| type.equals("25")|| type.equals("41")|| type.equals("42")|| type.equals("43")|| type.equals("46"))
					{
						weatherIcon.setImageDrawable(getResources().getDrawable(R.drawable.snow));
					}
					else if(type.equals("20") || type.equals("21") || type.equals("22")|| type.equals("23")|| type.equals("24"))
					{
						weatherIcon.setImageDrawable(getResources().getDrawable(R.drawable.sun_lines));
					}
					else if(type.equals("32") || type.equals("34") || type.equals("3200"))
					{
						weatherIcon.setImageDrawable(getResources().getDrawable(R.drawable.sun));
					}
					else if(type.equals("31") || type.equals("33") || type.equals("27") || type.equals("29"))
					{
						weatherIcon.setImageDrawable(getResources().getDrawable(R.drawable.moon));
					}

					System.out.println("Weather Updated");			
				}
				
			}

			private void setWeatherImage(String type)
			{
				//type = type.toLowerCase();
				System.out.println("TYPE::::::::::::::"+type);
				
				
			}
		};
	}
   
	public Handler getWeatherHandler()
	{
		return handler;		
	}
   

    /* Starts Jon's location tracker
     */
    private OnClickListener checkrunStartPress = new OnClickListener() 
    {
        public void onClick(View v) 
        {
            Intent intent = new Intent(getBaseContext(), Run.class);
            if(timeChecked)
            {
                    intent.putExtra("goaltime", (60*npmins.getValue()*5 + 60*60*nphours.getValue()) );
                    dialogSetTime.dismiss();
            }
            else
            {
                    intent.putExtra("goaldist", npdist.getValue()*500 );
                    dialogSetDist.dismiss();
            }
            intent.putExtra("wm",new String[]{weather.getWeather_code(), weather.getWind_direction()});
            startActivity(intent);
        }
    };
    
    /* Checks if the Time run option is selected.
     * Creates buttons/listeners for the Time dialog Cancel and Go buttons
     * Value can be retrieved using .getValue()
     * Pickers are called np_mins and np_hours in dialog_time.xml (dialogSetTime object)
     */
    private OnClickListener checkTimeRunPress = new OnClickListener() 
    {
        public void onClick(View v) 
        {                       
        Button goButton = (Button)dialogSetTime.findViewById(R.id.go);
        goButton.setOnClickListener(checkrunStartPress);
        
        Button cancelButton = (Button)dialogSetTime.findViewById(R.id.cancel);
        cancelButton.setOnClickListener(closeTimeDia);
        
        nphours = (NumberPicker) dialogSetTime.findViewById(R.id.np_hours);
        nphours.setMaxValue(5);
        nphours.setMinValue(0);
        nphours.setWrapSelectorWheel(true);
        
        String[] nums = new String[12];
        
        for(int i=1; i<=nums.length; i++)
        {
           nums[i-1] = Integer.toString(i*5);
        }
        
        npmins = (NumberPicker) dialogSetTime.findViewById(R.id.np_mins);
        npmins.setMaxValue(nums.length-1);
        npmins.setMinValue(1);
        npmins.setWrapSelectorWheel(false);
        npmins.setDisplayedValues(nums);
        npmins.setWrapSelectorWheel(true);
        
        timeChecked = true;
                dialogSetTime.show();
                
        }
    };
    
    /* Listens for Time dialog cancel button, and closes the dialog
     */
    private OnClickListener closeTimeDia = new OnClickListener() 
    {
        public void onClick(View v) 
        {
                timeChecked = false;
                dialogSetTime.dismiss();                        
        }
    };
    
    
    /* Checks if the Distance run option is selected.
     * Creates buttons/listeners for the Distance dialog Cancel and Go buttons
     * Value can be retrieved using .getValue()
     * Pickers called np_dist in dialog_dist.xml
     */
    private OnClickListener checkDistRunPress = new OnClickListener() 
    {
        public void onClick(View v) 
        {
                Button goButton = (Button)dialogSetDist.findViewById(R.id.go);
        goButton.setOnClickListener(checkrunStartPress);
        
        Button cancelButton = (Button)dialogSetDist.findViewById(R.id.cancel);
        cancelButton.setOnClickListener(closeDistDia);
                        
        String[] dists = new String[40];
        
        for(int i=1; i<=dists.length; i++)
        {
           dists[i-1] = Integer.toString(i*500);
        }
        
        npdist = (NumberPicker) dialogSetDist.findViewById(R.id.np_dist);
        npdist.setMaxValue(dists.length-1);
        npdist.setMinValue(1);
        npdist.setWrapSelectorWheel(false);
        npdist.setDisplayedValues(dists);
        npdist.setWrapSelectorWheel(true);

        timeChecked = false;
        dialogSetDist.show();
        }
    };
    
    /* Listens for Distance dialog cancel button, and closes the dialog
     */
    private OnClickListener closeDistDia = new OnClickListener() 
    {
        public void onClick(View v) 
        {                            

        	timeChecked = true;
                dialogSetDist.dismiss();                        
        }
    };   
	
	protected void setupProgressBar()
	{	       
		DbManager db = new DbManager(this);
		Player player = new Player(db);
		int percentage = player.getProgressBarPercentage();
		int lvl = player.getLevel();	 
				
		((ProgressBar)findViewById (R.id.progressBar)).setProgress(percentage);			
		((TextView)findViewById (R.id.level_lower_text)).setText(""+lvl);		
		((TextView)findViewById (R.id.level_upper_text)).setText(""+(lvl+1));
	}
    

    
    
    
}
